<template>
  <div v-if="team">
    <van-cell-group inset style="margin-top: 10px">
    <van-cell title="队伍名称" :value="team?.name" />
    <van-cell title="队伍描述" :value="team?.description"/>
    <van-cell title="过期时间" class="last-cell"
              :value="moment(team.expireTime).format('YYYY-MM-DD HH:mm:ss')"/>
    <van-cell title="队伍最大人数" :value="team?.maxNum" />
    <van-cell title="创建时间" class="last-cell"
              :value="moment(team.createTime).format('YYYY-MM-DD HH:mm:ss')"/>
    <van-cell title="队长" :value="(team?.createUserName ? `${team?.createUserName}` : `null`)" />
    <van-cell title="队伍人数" :value="team?.joinNum" />
    </van-cell-group>
    <div style="margin: 16px">
      <div v-if="team.userId!==currentUser?.id">
        <div v-if="!key">
          <van-button  style="width: 80%;margin-left: 40px;margin-top: 10px" round type="primary"
                       @click="preJoinTeam(team)">
            加入队伍
          </van-button>
        </div>
        <div v-else>
          <van-button  style="width: 80%;margin-left: 40px;margin-top: 10px" round type="warning" plain
                       @click="doJoinChat(team)">
            加入聊天室
          </van-button>
          <van-button style="width: 80%;margin-left: 40px;margin-top: 10px" round type="primary"
                    @click="doQuitTeam(team.teamId)">退出队伍
          </van-button>
        </div>
      </div>
        <div v-else>
          <van-button  style="width: 80%;margin-left: 40px;margin-top: 10px" round type="warning" plain
                       @click="doJoinChat(team)">
            加入聊天室
          </van-button>
          <van-button style="width: 80%;margin-left: 40px;margin-top: 10px" round type="primary"
                      @click="doUpdateTeam(team.teamId)">更新队伍
          </van-button>
          <van-button type="danger"  style="width: 80%;margin-left: 40px;margin-top: 10px" round
                      @click="doDeleteTeam(team.teamId)">解散队伍
          </van-button>

        </div>
    </div>
    <van-dialog v-model:show="showPasswordDialog" title="请输入密码" show-cancel-button @confirm="doJoinTeam" @cancel="doJoinCancel">
      <van-field v-model="password" placeholder="请输入密码"/>
    </van-dialog>
  </div>

</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import moment from "moment";
import {onMounted, ref} from "vue";
import myAxios from "../../plugins/myAxios";
import {Toast} from "@vant/compat";
import {getCurrentUser} from "../../services/user";

const router= useRouter();
const route = useRoute();


const team = ref({
  teamId: Number(route.query.teamId),
  userId: Number(route.query.userId),
  name: route.query.name,
  description: route.query.description,
  expireTime: route.query.expireTime,
  maxNum: route.query.maxNum,
  status: route.query.status,
  createTime: route.query.createTime,
  createUserName: route.query.createUserName,
  joinNum: route.query.joinNum,
});


const showPasswordDialog = ref(false);
const password = ref('');
const joinTeamId = ref(0);
const currentUser = ref();
const key=ref();



onMounted(async () => {
  currentUser.value = await getCurrentUser();
  const hasJoin=await myAxios.get('/team/hasJoin', {
    params:{
      teamId :team.value.teamId
    }
  });
  key.value=hasJoin.data
})



const doJoinChat =  (team) => {

      // 进入聊天室界面，建立ws连接
      router.push({
        path: '/chat',
        query: {
          toUserId: team.teamId,
          receiveType: 1,
          status: team.status
        }
      })
}

const preJoinTeam = (team) => {
  console.log(team.teamId)
  joinTeamId.value = team.teamId;
  if (team.status === "0") {
    doJoinTeam()
  } else {
    showPasswordDialog.value = true;
  }
}

const doJoinCancel = () => {
  joinTeamId.value = 0;
  password.value = '';
}


/**
 * 退出队伍
 * @param id
 */
const doQuitTeam = async (id: number) => {
  const res = await myAxios.post('/team/quit', {
    teamId: id
  });
  if (res?.code === 0) {
    window.location.reload();
    Toast.success('操作成功');
  } else {
    Toast.fail('操作失败' + (res.description ? `，${res.description}` : ''));
  }
}

/**
 * 解散队伍
 * @param id
 */
const doDeleteTeam = async (id: number) => {
  const res = await myAxios.get('/team/delete', {
    params:{
      teamId :id
    }
  });
  if (res?.code === 0) {
    window.location.href=`/team`;
    Toast.success('操作成功');
  } else {
    Toast.fail('操作失败' + (res.description ? `，${res.description}` : ''));
  }
}
/**
 * 加入队伍
 */
const doJoinTeam = async () => {
  if (!joinTeamId.value) {
    return;
  }
  const res = await myAxios.post('/team/join', {
    teamId: joinTeamId.value,
    password: password.value
  });
  if (res?.code === 0) {
    window.location.reload()
    Toast.success('加入成功');
    doJoinCancel();
  } else {
    Toast.fail('加入失败' + (res.description ? `，${res.description}` : ''));
  }
}
/**
 * 跳转至更新队伍页
 * @param id
 */
const doUpdateTeam = (id: number) => {
  router.push({
    path: '/team/update',
    query: {
      "teamId":id,
    }
  })
}
</script>

<style scoped>

</style>